package com.xbfinal.email.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xbfinal.email.service.MsmService;
import com.xbfinal.email.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Title: MsmServiceImpl
 * @Author 笑霸fianl
 * @Package com.xbfinal.email.controller.service.impl
 * @Date 2023/2/28 9:20
 * @描述:
 */
@Slf4j
@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String myFrom;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean send(String phone) {


        if (!StrUtil.isEmpty(phone)){
            //先取redis中的数据
            String myCode = redisTemplate.opsForValue().get("phone");
            if(!StrUtil.isEmpty(myCode)){
                return true;
            }

            //生成随机的值传给邮件服务
            String code = RandomUtil.getSixBitRandom();

            log.info("==========");
            //验证码
            log.info(code);
            log.info("==========");

            //创建简单邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            //用自己的邮件发
            message.setFrom(myFrom);
            //谁要接收
            message.setTo(phone);
            //邮件标题
            message.setSubject("验证码");
            //邮件内容
            message.setText("你的验证码是："+code+"请不要转发给他人 5分钟内有效");
            try {
                mailSender.send(message);
                //验证码放入redis并设置过期时间
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
                return true;
            }catch (Exception e){
                return false;
            }

        }


        return false;
    }
}
